package com.gzx.bi.modular.agent.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.gzx.bi.modular.agent.bo.GzxAgentEffectBo;
import com.gzx.bi.modular.agent.entity.GzxAgentEffect;
import com.gzx.bi.modular.agent.mapper.GzxAgentEffectMapper;
import com.gzx.bi.modular.agent.service.GzxAgentEffectService;
import com.gzx.bi.modular.agent.vo.GzxAgentCallPercentageVo;
import com.gzx.bi.modular.agent.vo.GzxAgentEffectVo;
import com.gzx.bi.modular.agent.vo.GzxAgentHourlyWorkloadVo;
import com.gzx.bi.modular.screen.entity.GzxHtCallReceiptBusiness;
import com.gzx.bi.modular.team.bo.GzxTeamEffectBo;
import com.gzx.bi.modular.user.service.GzxUserDebtService;
import com.gzx.bi.modular.user.vo.GzxUserDebtVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 团队效率
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GzxAgentEffectServiceImpl implements GzxAgentEffectService {

    private final GzxAgentEffectMapper gzxAgentEffectMapper;

    private final GzxUserDebtService gzxUserDebtService;

    /**
     * 通话时长占比
     */
    @DS("bi")
    @Override
    public List<GzxAgentCallPercentageVo> getCallPercentage(GzxTeamEffectBo bo) {
        List<GzxAgentCallPercentageVo> list = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(bo.getBelongProject())) {
            bo.setBelongProject("('" + bo.getBelongProject().replaceAll(",", "','") + "')");
        }
        GzxAgentCallPercentageVo vo = gzxAgentEffectMapper.getCallPercentage(bo);
        //list里面的数据加在一起不到100%，填充一行其它数据
        if (vo != null) {
            double sum = vo.getEffectTen() + vo.getEffectThirty() + vo.getEffectSixty() + vo.getEffectMore();
            if (sum > 0 && sum < 1) {
                vo.setEffectOther(1 - sum);
            } else if (sum > 1 && sum < 100) {
                vo.setEffectOther(100 - sum);
            }
            list.add(vo);
        }
        return list;
    }

    /**
     * 各时点外呼工作量及接通率
     */
    @DS("bi")
    @Override
    public List<GzxAgentHourlyWorkloadVo> getHourlyWorkload(GzxTeamEffectBo bo) {
        if (ObjectUtil.isNotEmpty(bo.getBelongProject())) {
            bo.setBelongProject("('" + bo.getBelongProject().replaceAll(",", "','") + "')");
        }
        return gzxAgentEffectMapper.getHourlyWorkload(bo);
    }

    /**
     * 坐席效率
     */
    @DS("bi")
    @Override
    public List<GzxAgentEffectVo> getAgentEffect(GzxAgentEffectBo bo) {
        //项目代码是逗号分隔的，手动拼接成in的结果
        if (ObjectUtil.isNotEmpty(bo.getBelongProject())) {
            bo.setBelongProject("('" + bo.getBelongProject().replaceAll(",", "','") + "')");
        }
        return gzxAgentEffectMapper.getAgentEffect(bo);
    }

    /**
     * 坐席效率报表
     */
    @DS("bi")
    @Override
    public void saveAgentBatch(List<ConsumerRecord<String, String>> recordList) {
        //把话单转成对象
        List<GzxHtCallReceiptBusiness> list = recordList.stream().map(rowData -> JSON.parseObject(rowData.value(), GzxHtCallReceiptBusiness.class)).toList();
        log.info("从MQ中批量获取话单：本批次处理event数量{}", list.size());

        //获取坐席的所属项目，小组
        List<GzxUserDebtVo> userDebtList = gzxUserDebtService.getUserDebt(list);
        log.info("获取坐席的所属项目，小组：{}", userDebtList.size());

        //保存报表数据
        list.forEach(record -> {
            GzxAgentEffect agent = new GzxAgentEffect();
            // 从userDebtList中筛选出account等于team.agentNum的对象
            List<GzxUserDebtVo> userDebtVos = userDebtList.stream()
                    .filter(userDebt -> userDebt != null && userDebt.getAccount() != null && userDebt.getAccount().equals(record.getAgentNum()))
                    .toList();
            GzxUserDebtVo userDebtVo = new GzxUserDebtVo();
            if (!userDebtVos.isEmpty()) {
                userDebtVo = userDebtVos.getFirst();
            }
            if (ObjectUtil.isNotEmpty(userDebtVo.getBelongProject())) {
                agent.setBelongTeam(userDebtVo.getBelongTeam());
                agent.setBelongProject(userDebtVo.getBelongProject());
            } else {
                //关联不到项目的坐席，跳过，个人中心那里一定要配置所属项目
                return;
            }
            //封装agent对象
            agent.setAgentNum(record.getAgentNum());
            //接通
            int connectNum = 0;
            //有效通话时长
            int effectDuration = 0;

            //拨打
            int calloutNum = 0;
            if (0 != record.getCallType()) {
                calloutNum = 1;
            }
            int duration = record.getCallDuration();
            if (duration > 0) {
                connectNum = 1;
            }
            if (duration > 0 && duration < 10) {
                effectDuration = duration;
                agent.setEffectTen(duration);
            } else if (duration > 10 && duration < 30) {
                agent.setEffectThirty(duration);
            } else if (duration > 30 && duration < 60) {
                agent.setEffectSixty(duration);
            } else if (duration > 60) {
                agent.setEffectMore(duration);
            }
            agent.setCalloutNum(calloutNum);
            agent.setConnectNum(connectNum);
            agent.setConnectDuration(duration);
            agent.setEffectDuration(effectDuration);

            gzxAgentEffectMapper.insertUpdate(agent);
        });

    }
}
